use std::{
    fmt::{Display, Formatter},
    marker::PhantomData, hash::{Hasher,Hash},
};

use serde::{Deserialize, Serialize};

const INVALID_GENERATION: usize = 0;

pub trait PayloadWrap: Sized {
    type Element: Sized;

    fn new_empty() -> Self;

    fn new(element: Self::Element) -> Self;

    fn is_some(&self) -> bool;

    fn as_ref(&self) -> Option<&Self::Element>;

    fn as_mut(&mut self) -> Option<&mut Self::Element>;

    fn replace(&mut self, element: Self::Element) -> Option<Self::Element>;

    fn take(&mut self) -> Option<Self::Element>;
}

impl<T> PayloadWrap for Option<T> {
    type Element = T;

    fn new_empty() -> Self {
        Self::None
    }

    fn new(element: Self::Element) -> Self {
        Self::Some(element)
    }

    fn is_some(&self) -> bool {
        Option::is_some(&self)
    }

    fn as_ref(&self) -> Option<&Self::Element> {
        Option::as_ref(&self)
    }

    fn as_mut(&mut self) -> Option<&mut Self::Element> {
        Option::as_mut(self)
    }

    fn replace(&mut self, element: Self::Element) -> Option<Self::Element> {
        Option::replace(self, element)
    }

    fn take(&mut self) -> Option<Self::Element> {
        Option::take(self)
    }
}

#[derive(Debug, PartialOrd, Ord, Serialize, Deserialize)]
pub struct Handle<T> {
    pub(crate) index:       usize,
    pub(crate) generation:  usize,
    type_mark:              PhantomData<T>,
}

impl<T> Handle<T> {
    
}

unsafe impl<T> Send for Handle<T> {}
unsafe impl<T> Sync for Handle<T> {}

impl<T> Display for Handle<T> {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}", self.index, self.generation)
    }
}

#[derive(Copy, Clone, Debug, Ord, PartialOrd, PartialEq, Eq, Hash)]
pub struct ErasedHandle {
    pub(crate) index: usize,
    pub(crate) generation: usize,
}

impl Default for ErasedHandle {
    fn default() -> Self {
        Self { index: 0, generation: INVALID_GENERATION }
    }
}

impl<T> From<ErasedHandle> for Handle<T> {
    fn from(erased_handle: ErasedHandle) -> Self {
        Handle {
            index: erased_handle.index,
            generation: erased_handle.generation,
            type_mark: PhantomData,
        }
    }
}

impl<T> From<Handle<T>> for ErasedHandle {
    fn from(h: Handle<T>) -> Self {
        Self {
            index: h.index,
            generation: h.generation,
        }
    }
}


impl ErasedHandle {
    pub fn none() -> Self {
        Self {
            index: 0,
            generation: INVALID_GENERATION,
        }
    }

    pub fn new(value: usize, generation: usize) -> Self {
        Self { index: value, generation }
    }

    #[inline(always)]
    pub fn is_some(&self) -> bool {
        self.generation != INVALID_GENERATION
    }

    #[inline(always)]
    pub fn is_none(&self) -> bool {
        !self.is_some()
    }

    #[inline(always)]
    pub fn value(self) -> usize {
        self.index
    }

    #[inline(always)]
    pub fn generation(self) -> usize {
        self.generation
    }
}

impl<T> Default for Handle<T> {
    fn default() -> Self {
        Handle {
            index: 0,
            generation: 1,
            type_mark: PhantomData,
        }
    }
}

impl<T> Handle<T> {
    /// 尝试获取默认值的句柄 ，（只有设置默认值才能获取到准确的句柄）
    pub fn try_get_default_handle() -> Self {
        Handle {
            index: 0,
            generation: 1,
            type_mark: PhantomData,
        }
    }
    pub const NONE: Handle<T> = Handle {
        index: 0,
        generation: INVALID_GENERATION,
        type_mark: PhantomData,
    };

    #[inline(always)]
    pub fn is_none(self) -> bool {
        self.index == 0 && self.generation == INVALID_GENERATION
    }

    #[inline(always)]
    pub fn is_some(self) -> bool {
        !self.is_none()
    }

    #[inline(always)]
    pub fn value(self) -> usize {
        self.index
    }

    #[inline(always)]
    pub fn generation(self) -> usize {
        self.generation
    }

    #[inline(always)]
    pub fn new(value: usize, generation: usize) -> Self {
        Handle {
            index: value,
            generation,
            type_mark: PhantomData,
        }
    }
}
impl<T> Hash for Handle<T> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.index.hash(state);
        self.generation.hash(state);
    }
}

impl<T> Clone for Handle<T> {
    fn clone(&self) -> Handle<T> {
        Handle {
            index: self.index,
            generation: self.generation,
            type_mark: PhantomData,
        }
    }
}

impl<T> Copy for Handle<T> {}

impl<T> Eq for Handle<T> {}

impl<T> PartialEq for Handle<T> {
    fn eq(&self, other: &Handle<T>) -> bool {
        self.generation == other.generation && self.index == other.index
    }
}


pub struct Pool<T, P = Option<T>>
where
    T: Sized,
    P: PayloadWrap<Element = T>,
{
    records:        Vec<Record<T,P>>,
    free_stack:     Vec<usize>,
}

pub struct Record<T, P = Option<T>>
where
    T: Sized,
    P: PayloadWrap<Element = T>,
{
    generation: usize,
    payload: P,
}


impl<T: PartialEq> PartialEq for Record<T> {
    fn eq(&self, other: &Self) -> bool {
        self.generation == other.generation && self.payload == other.payload
    }
}


impl<T, P> Default for Record<T, P>
where
    P: PayloadWrap<Element = T> + 'static,
{
    fn default() -> Self {
        Self {
            generation: INVALID_GENERATION,
            payload:    P::new_empty(),
        }
    }
}



impl<T, P> Pool<T, P>
where
    T: std::fmt::Debug,
    P: PayloadWrap<Element = T> + 'static,
{
    #[inline]
    pub fn new() -> Self {
        Pool {
            records:        Vec::new(),
            free_stack:     Vec::new(),
        }
    }

    #[inline]
    pub fn with_capacity(capacity: usize) -> Self {
        let capacity = usize::try_from(capacity).expect("capacity overflowed usize");
        Pool {
            records:    Vec::with_capacity(capacity),
            free_stack: Vec::new(),
        }
    }

    fn records_len(&self) -> usize {
        usize::try_from(self.records.len()).expect("Number of records overflowed usize")
    }

    fn records_get(&self, value: usize) -> Option<&Record<T, P>> {
        let value = usize::try_from(value).expect("Index overflowed usize");
        self.records.get(value)
    }

    fn records_get_mut(&mut self, value: usize) -> Option<&mut Record<T, P>> {
        let value = usize::try_from(value).expect("Index overflowed usize");
        self.records.get_mut(value)
    }

    #[inline]
    #[must_use]
    pub fn spawn(&mut self, payload: T) -> Handle<T> {
        self.spawn_with(|_| payload)
    }

    /// Tries to put an object in the pool at given position. Returns `Err(payload)` if a corresponding
    /// entry is occupied.
    ///
    /// # Performance
    ///
    /// The method has O(n) complexity in worst case, where `n` - amount of free records in the pool.
    /// In typical uses cases `n` is very low. It should be noted that if a pool is filled entirely
    /// and you trying to put an object at the end of pool, the method will have O(1) complexity.
    ///
    /// # Panics
    ///
    /// Panics if the value is occupied or reserved (e.g. by [`take_reserve`]).
    ///
    /// [`take_reserve`]: Pool::take_reserve
    #[inline]
    pub fn spawn_at(&mut self, value: usize, payload: T) -> Result<Handle<T>, T> {
        self.spawn_at_internal(value, INVALID_GENERATION, payload)
    }

    /// Tries to put an object in the pool at given handle. Returns `Err(payload)` if a corresponding
    /// entry is occupied.
    ///
    /// # Performance
    ///
    /// The method has O(n) complexity in worst case, where `n` - amount of free records in the pool.
    /// In typical uses cases `n` is very low. It should be noted that if a pool is filled entirely
    /// and you trying to put an object at the end of pool, the method will have O(1) complexity.
    ///
    /// # Panics
    ///
    /// Panics if the value is occupied or reserved (e.g. by [`take_reserve`]).
    ///
    /// [`take_reserve`]: Pool::take_reserve
    pub fn spawn_at_handle(&mut self, handle: Handle<T>, payload: T) -> Result<Handle<T>, T> {
        self.spawn_at_internal(handle.index, handle.generation, payload)
    }

    fn spawn_at_internal(
        &mut self,
        value: usize,
        desired_generation: usize,
        payload: T,
    ) -> Result<Handle<T>, T> {
        let index_usize = usize::try_from(value).expect("value overflowed usize");
        match self.records.get_mut(index_usize) {
            Some(record) => match record.payload.as_ref() {
                Some(_) => Err(payload),
                None => {
                    let position = self
                        .free_stack
                        .iter()
                        .rposition(|i| *i == value)
                        .expect("free_stack must contain the value of the empty record (most likely attempting to spawn at a reserved value)!");

                    self.free_stack.remove(position);

                    let generation = if desired_generation == INVALID_GENERATION {
                        record.generation + 1
                    } else {
                        desired_generation
                    };

                    record.generation = generation;
                    record.payload = P::new(payload);

                    Ok(Handle::new(value, generation))
                }
            },
            None => {
                // Spawn missing records to fill gaps.
                for i in self.records_len()..value {
                    self.records.push(Record {
                        generation: 1,
                        payload: P::new_empty(),
                    });
                    self.free_stack.push(i);
                }

                let generation = if desired_generation == INVALID_GENERATION {
                    1
                } else {
                    desired_generation
                };

                self.records.push(Record {
                    generation,
                    payload: P::new(payload),
                });

                Ok(Handle::new(value, generation))
            }
        }
    }

    #[inline]
    #[must_use]
    /// Construct a value with the handle it would be given.
    /// Note: Handle is _not_ valid until function has finished executing.
    pub fn spawn_with<F: FnOnce(Handle<T>) -> T>(&mut self, callback: F) -> Handle<T> {
        if let Some(free_index) = self.free_stack.pop() {
            let record = self
                .records_get_mut(free_index)
                .expect("free stack contained invalid value");

            if record.payload.is_some() {
                panic!(
                    "Attempt to spawn an object at pool record with payload! Record value is {}",
                    free_index
                );
            }

            let generation = record.generation + 1;
            let handle = Handle {
                index: free_index,
                generation,
                type_mark: PhantomData,
            };

            let payload = callback(handle);

            record.generation = generation;
            record.payload.replace(payload);
            handle
        } else {
            // No free records, create new one
            let generation = 1;

            let handle = Handle {
                index: self.records.len(),
                generation,
                type_mark: PhantomData,
            };

            let payload = callback(handle);

            let record = Record {
                generation,
                payload: P::new(payload),
            };

            self.records.push(record);

            handle
        }
    }
/// Borrows shared reference to an object by its handle.
    ///
    /// # Panics
    ///
    /// Panics if handle is out of bounds or generation of handle does not match with
    /// generation of pool record at handle value (in other words it means that object
    /// at handle's value is different than the object was there before).
    #[inline]
    #[must_use]
    pub fn borrow(&self, handle: Handle<T>) -> &T {
        if let Some(record) = self.records_get(handle.index) {
            if record.generation == handle.generation {
                if let Some(payload) = record.payload.as_ref() {
                    payload
                } else {
                    panic!("Attempt to borrow destroyed object at {:?} handle.", handle);
                }
            } else {
                panic!(
                    "Attempt to use dangling handle {:?}. Record has generation {}!",
                    handle, record.generation
                );
            }
        } else {
            panic!(
                "Attempt to borrow object using out-of-bounds handle {:?}! Record count is {}",
                handle,
                self.records.len()
            );
        }
    }

    /// Borrows mutable reference to an object by its handle.
    ///
    /// # Panics
    ///
    /// Panics if handle is out of bounds or generation of handle does not match with
    /// generation of pool record at handle value (in other words it means that object
    /// at handle's value is different than the object was there before).
    ///
    /// # Example
    ///
    /// ```
    /// use fyrox_core::pool::Pool;
    /// let mut pool = Pool::<u32>::new();
    /// let a = pool.spawn(1);
    /// let a = pool.borrow_mut(a);
    /// *a = 11;
    /// ```
    #[inline]
    #[must_use]
    pub fn borrow_mut(&mut self, handle: Handle<T>) -> &mut T {
        let record_count = self.records.len();
        if let Some(record) = self.records_get_mut(handle.index) {
            if record.generation == handle.generation {
                if let Some(payload) = record.payload.as_mut() {
                    payload
                } else {
                    panic!("Attempt to borrow destroyed object at {:?} handle.", handle);
                }
            } else {
                panic!("Attempt to borrow object using dangling handle {:?}. Record has {} generation!", handle, record.generation);
            }
        } else {
            panic!(
                "Attempt to borrow object using out-of-bounds handle {:?}! Record count is {}",
                handle, record_count
            );
        }
    }

    /// Borrows shared reference to an object by its handle.
    ///
    /// Returns None if handle is out of bounds or generation of handle does not match with
    /// generation of pool record at handle value (in other words it means that object
    /// at handle's value is different than the object was there before).
    #[inline]
    #[must_use]
    pub fn try_borrow(&self, handle: Handle<T>) -> Option<&T> {
        self.records_get(handle.index).and_then(|r| {
            if r.generation == handle.generation {
                r.payload.as_ref()
            } else {
                None
            }
        })
    }

    /// Borrows mutable reference to an object by its handle.
    ///
    /// Returns None if handle is out of bounds or generation of handle does not match with
    /// generation of pool record at handle value (in other words it means that object
    /// at handle's value is different than the object was there before).
    #[inline]
    #[must_use]
    pub fn try_borrow_mut(&mut self, handle: Handle<T>) -> Option<&mut T> {
        self.records_get_mut(handle.index).and_then(|r| {
            if r.generation == handle.generation {
                r.payload.as_mut()
            } else {
                None
            }
        })
    }

    /// Borrows mutable references of objects at the same time. This method will succeed only
    /// if handles are unique (not equal). Borrowing multiple mutable references at the same
    /// time is useful in case if you need to mutate some objects at the same time.
    ///
    /// # Panics
    ///
    /// See [`borrow_mut`](Self::borrow_mut).
    ///
    /// # Example
    ///
    /// ```
    /// use fyrox_core::pool::Pool;
    /// let mut pool = Pool::<u32>::new();
    /// let a = pool.spawn(1);
    /// let b = pool.spawn(2);
    /// let (a, b) = pool.borrow_two_mut((a, b));
    /// *a = 11;
    /// *b = 22;
    /// ```
    #[inline]
    #[must_use = "Handle set must not be ignored"]
    pub fn borrow_two_mut(&mut self, handles: (Handle<T>, Handle<T>)) -> (&mut T, &mut T) {
        // Prevent giving two mutable references to same record.
        assert_ne!(handles.0.index, handles.1.index);
        unsafe {
            let this = self as *mut Self;
            ((*this).borrow_mut(handles.0), (*this).borrow_mut(handles.1))
        }
    }

    /// Borrows mutable references of objects at the same time. This method will succeed only
    /// if handles are unique (not equal). Borrowing multiple mutable references at the same
    /// time is useful in case if you need to mutate some objects at the same time.
    ///
    /// # Panics
    ///
    /// See [`borrow_mut`](Self::borrow_mut).
    ///
    /// # Example
    ///
    /// ```
    /// use fyrox_core::pool::Pool;
    /// let mut pool = Pool::<u32>::new();
    /// let a = pool.spawn(1);
    /// let b = pool.spawn(2);
    /// let c = pool.spawn(3);
    /// let (a, b, c) = pool.borrow_three_mut((a, b, c));
    /// *a = 11;
    /// *b = 22;
    /// *c = 33;
    /// ```
    #[inline]
    #[must_use = "Handle set must not be ignored"]
    pub fn borrow_three_mut(
        &mut self,
        handles: (Handle<T>, Handle<T>, Handle<T>),
    ) -> (&mut T, &mut T, &mut T) {
        // Prevent giving mutable references to same record.
        assert_ne!(handles.0.index, handles.1.index);
        assert_ne!(handles.0.index, handles.2.index);
        assert_ne!(handles.1.index, handles.2.index);
        unsafe {
            let this = self as *mut Self;
            (
                (*this).borrow_mut(handles.0),
                (*this).borrow_mut(handles.1),
                (*this).borrow_mut(handles.2),
            )
        }
    }

    /// Borrows mutable references of objects at the same time. This method will succeed only
    /// if handles are unique (not equal). Borrowing multiple mutable references at the same
    /// time is useful in case if you need to mutate some objects at the same time.
    ///
    /// # Panics
    ///
    /// See [`borrow_mut`](Self::borrow_mut).
    ///
    /// # Example
    ///
    /// ```
    /// use fyrox_core::pool::Pool;
    /// let mut pool = Pool::<u32>::new();
    /// let a = pool.spawn(1);
    /// let b = pool.spawn(2);
    /// let c = pool.spawn(3);
    /// let d = pool.spawn(4);
    /// let (a, b, c, d) = pool.borrow_four_mut((a, b, c, d));
    /// *a = 11;
    /// *b = 22;
    /// *c = 33;
    /// *d = 44;
    /// ```
    #[inline]
    #[must_use = "Handle set must not be ignored"]
    pub fn borrow_four_mut(
        &mut self,
        handles: (Handle<T>, Handle<T>, Handle<T>, Handle<T>),
    ) -> (&mut T, &mut T, &mut T, &mut T) {
        // Prevent giving mutable references to same record.
        // This is kinda clunky since const generics are not stabilized yet.
        assert_ne!(handles.0.index, handles.1.index);
        assert_ne!(handles.0.index, handles.2.index);
        assert_ne!(handles.0.index, handles.3.index);
        assert_ne!(handles.1.index, handles.2.index);
        assert_ne!(handles.1.index, handles.3.index);
        assert_ne!(handles.2.index, handles.3.index);
        unsafe {
            let this = self as *mut Self;
            (
                (*this).borrow_mut(handles.0),
                (*this).borrow_mut(handles.1),
                (*this).borrow_mut(handles.2),
                (*this).borrow_mut(handles.3),
            )
        }
    }

    /// Tries to borrow two objects when a handle to the second object stored in the first object.
    pub fn try_borrow_dependant_mut<F>(
        &mut self,
        handle: Handle<T>,
        func: F,
    ) -> (Option<&mut T>, Option<&mut T>)
    where
        F: FnOnce(&T) -> Handle<T>,
    {
        let this = unsafe { &mut *(self as *mut Pool<T, P>) };
        let first = self.try_borrow_mut(handle);
        if let Some(first_object) = first.as_ref() {
            let second_handle = func(first_object);
            if second_handle != handle {
                return (first, this.try_borrow_mut(second_handle));
            }
        }

        (first, None)
    }

    /// Moves object out of the pool using the given handle. All handles to the object will become invalid.
    ///
    /// # Panics
    ///
    /// Panics if the given handle is invalid.
    #[inline]
    pub fn free(&mut self, handle: Handle<T>) -> T {
        let value = usize::try_from(handle.index).expect("value overflowed usize");
        if let Some(record) = self.records.get_mut(value) {
            if record.generation == handle.generation {
                // Remember this value as free
                self.free_stack.push(handle.index);
                // Return current payload.
                if let Some(payload) = record.payload.take() {
                    payload
                } else {
                    panic!("Attempt to double free object at handle {:?}!", handle);
                }
            } else {
                panic!(
                    "Attempt to free object using dangling handle {:?}! Record generation is {}",
                    handle, record.generation
                );
            }
        } else {
            panic!("Attempt to free destroyed object using out-of-bounds handle {:?}! Record count is {}", handle, self.records.len());
        }
    }

    /// Tries to move object out of the pool using the given handle. Returns None if given handle
    /// is invalid. After object is moved out if the pool, all handles to the object will become
    /// invalid.
    #[inline]
    pub fn try_free(&mut self, handle: Handle<T>) -> Option<T> {
        let value = usize::try_from(handle.index).expect("value overflowed usize");
        self.records.get_mut(value).and_then(|record| {
            if record.generation == handle.generation {
                if let Some(payload) = record.payload.take() {
                    self.free_stack.push(handle.index);
                    Some(payload)
                } else {
                    None
                }
            } else {
                None
            }
        })
    }

}